package com.rk.hosp.aop;
import com.alibaba.excel.util.StringUtils;
import com.rk.common.exception.YyghException;
import com.rk.common.helper.HttpRequestHelper;
import com.rk.common.result.ResultCodeEnum;
import com.rk.common.utils.MD5;
import com.rk.hosp.service.HospitalSetService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author :Rk.
 * @date : 2022/11/12
 */
@Aspect
@Slf4j
@Component
public class CheckSignAspect {


    @Autowired
    private HospitalSetService hospitalSetService;


    /**
     * 定义切入点
     */
    @Pointcut("@annotation(SystemCheckSign)")
    public void controllerAspect(){

    }

    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint){
        log.info("--------------开始校验签名----------------");
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();

        //获取传递过来的医院的信息
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(request.getParameterMap());

        // 校验 签名
        //前端传递过来的签名
        String sign =(String) paramMap.get("sign");
        //前端传递过来的医院编码 通过医院编码查询数据库中的签名 并且 判断该医院是否存在
        String hoscode = (String)paramMap.get("hoscode");


        //如果为空 就抛出异常
        if(StringUtils.isEmpty(sign)||StringUtils.isEmpty(hoscode))
        {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //去查询数据库中的签名
        String signKey = hospitalSetService.getSignKey(hoscode);
        // 3、把数据库查询出来的签名进行md5加密
        String signKeyMd5 = MD5.encrypt(signKey);

        // 4、判断是否一致  如果不一样
        if(!sign.equals(signKeyMd5)){
            throw new YyghException(ResultCodeEnum.SIGN_ERROR);
        }else {
            log.info("--------------签名校验通过---------------");
        }
    }


}
